package com.card.client.dialog;

import java.util.ArrayList;
import java.util.Date;

import com.card.client.entry.CreditCard;
import com.card.client.entry.CreditCardBill;
import com.card.client.entry.Util;
import com.card.client.service.CreditCardBillService;
import com.card.client.service.CreditCardBillServiceAsync;
import com.card.client.service.CreditCardService;
import com.card.client.service.CreditCardServiceAsync;
import com.card.client.view.CreditCardBillInfoView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DateBox.DefaultFormat;

public class EditCreditCardBillDialog extends DialogBox {

	private static EditCreditCardBillDialogUiBinder uiBinder = GWT.create(EditCreditCardBillDialogUiBinder.class);

	interface EditCreditCardBillDialogUiBinder extends UiBinder<Widget, EditCreditCardBillDialog> {
	}
	
	private final CreditCardBillServiceAsync ccbs = GWT.create(CreditCardBillService.class);
	
	private final CreditCardServiceAsync ccs = GWT.create(CreditCardService.class);
	
	private Long id;

	@UiField ListBox cardName;
	
	@UiField ListBox financeMonth;
	
	@UiField DateBox lastRePayDate;
	
	@UiField DateBox rePayDate;
	
	@UiField TextBox minRePay;
	
	@UiField TextBox actualRePay;
	
	@UiField TextBox overAmount;
	
	@UiField TextBox interest;
	
	@UiField TextBox overCost;
	
	@UiField TextBox excess;
	
	@UiField TextBox takeAmount;
	
	@UiField DateBox takeDate;
	
	@UiField Button submit;
	
	@UiField Button closeDialog;
	
	@UiField Label message;
	
	public static int ADD = 0;
	
	public static int UPDATE = 1;
	
	CreditCardBillInfoView creditCardBillInfoView;
	
	CreditCardBill creditCardBill;
	
	public EditCreditCardBillDialog(String title, String descript, CreditCardBillInfoView creditCardBillInfoView, CreditCardBill cardBill, int flag) {
		setWidget(uiBinder.createAndBindUi(this));
		setTitle(title);
		setText(descript);
		setGlassEnabled(true);
		setAnimationEnabled(true);
		setModal(true);
		message.setStyleName("descript");
		center();
		minRePay.setMaxLength(Util.INPUT_TEXT_MAX_LENGTH);
		actualRePay.setMaxLength(Util.INPUT_TEXT_MAX_LENGTH);
		overAmount.setMaxLength(Util.INPUT_TEXT_MAX_LENGTH);
		interest.setMaxLength(Util.INPUT_TEXT_MAX_LENGTH);
		overCost.setMaxLength(Util.INPUT_TEXT_MAX_LENGTH);
		excess.setMaxLength(Util.INPUT_TEXT_MAX_LENGTH);
		takeAmount.setMaxLength(Util.INPUT_TEXT_MAX_LENGTH);
		DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy-MM-dd");
		DefaultFormat defaultFormat = new DefaultFormat(dateTimeFormat);
		lastRePayDate.setFormat(defaultFormat);
		rePayDate.setFormat(defaultFormat);
		takeDate.setFormat(defaultFormat);
		ccs.getAllCard(new AsyncCallback<CreditCard[]>() {
			public void onSuccess(CreditCard[] result) {
				if(result.length<1){
					cardName.addItem("没有卡片信息，不能添加账目", "0");
					submit.setEnabled(false);
				} else {
					cardName.addItem("", "0");
				}
				for(int i=0;i<result.length;i++){
					cardName.addItem(result[i].getName(), result[i].getItem());
				}
				if(creditCardBill!=null){
					int index = 0;
					for(int i=0;i<cardName.getItemCount();i++){
						String value = cardName.getValue(i);
						if(value.equals(creditCardBill.getItem())){
							index = i;
						}
					}
					cardName.setSelectedIndex(index);
				}
			}
			public void onFailure(Throwable caught) {}
		});
		this.creditCardBillInfoView = creditCardBillInfoView;
		setFinanceMonth();
		submit.setText("添加");
		if(flag == UPDATE){
			submit.setText("修改");
			this.creditCardBill = cardBill;
			setContent();
		}
		int w = minRePay.getOffsetWidth() + 1;
		cardName.setWidth(w + "px");
		financeMonth.setWidth(w + "px");
	}

	private void setFinanceMonth() {
		DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy-MM");
		String thisMonth = dateTimeFormat.format(new Date());
		String[] temp = thisMonth.split("-");
		String year = temp[0];
		String month = temp[1];
		int tm = Integer.parseInt(month);
		ArrayList<String> fm = new ArrayList<String>();
		if(tm<6){
			int index = 6-tm;
			int lastm = 13;
			int lasty = Integer.parseInt(year)-1;
			for(int i=index;i>0;i--){
				String ly = Integer.toString(lasty);
				String fmonth = null;
				if((lastm - i) < 10){
					fmonth = ly + "-0" + Integer.toString(lastm - i);
				} else {
					fmonth = ly + "-" + Integer.toString(lastm - i);
				}
				fm.add(fmonth);
			}
			for(int i=1;i<=tm;i++){
				String fmonth = null;
				if(i<10){
					fmonth = year + "-0" + Integer.toString(i);
				} else {
					fmonth = year + "-" + Integer.toString(i);
				}
				fm.add(fmonth);
			}
		} else {
			for(int i=5;i>=0;i--){
				String fmonth = null;
				if((tm - i) < 10){
					fmonth = year + "-0" + Integer.toString(tm - i);
				} else {
					fmonth = year + "-" + Integer.toString(tm - i);
				}
				fm.add(fmonth);
			}
		}
		financeMonth.addItem("", "0");
		for(int i=fm.size()-1;i>=0;i--){
			financeMonth.addItem(fm.get(i));
		}
	}

	@UiHandler("submit")
	void onClickSubmit(ClickEvent e) {
		if(!isValid()){
			return;
		}
		final CreditCardBill ccb = new CreditCardBill();
		ccb.setId(id);
		ccb.setItem(cardName.getValue(cardName.getSelectedIndex()));
		ccb.setLastRePayDate(lastRePayDate.getValue());
		ccb.setRePayDate(rePayDate.getValue());
		ccb.setMinRePay(Util.strToInt(minRePay.getText()));
		ccb.setActualRePay(Util.strToInt(actualRePay.getText()));
		ccb.setOverAmount(Util.strToInt(overAmount.getText()));
		ccb.setInterest(Util.strToInt(interest.getText()));
		ccb.setOverCost(Util.strToInt(overCost.getText()));
		ccb.setExcess(Util.strToInt(excess.getText()));
		ccb.setFinanceMonth(financeMonth.getItemText(financeMonth.getSelectedIndex()));
		ccb.setTakeAmount(Util.strToInt(takeAmount.getText()));
		ccb.setTakeDate(takeDate.getValue());
		if(null != id){
			ccbs.updateCreditCardBill(ccb, new AsyncCallback<Void>() {
				public void onSuccess(Void result) {
					hide();
					creditCardBillInfoView.onLoad(ccb.getFinanceMonth());
				}
				public void onFailure(Throwable caught) {}
			});
		} else {
			ccbs.addCreditCardBill(ccb, new AsyncCallback<Void>() {
				public void onSuccess(Void result) {
					hide();
					creditCardBillInfoView.onLoad(ccb.getFinanceMonth());
				}
				public void onFailure(Throwable caught) {}
			});
		}
	}

	@UiHandler("closeDialog")
	void onClickCloseDialog(ClickEvent e) {
		hide();
		if(id!=null){
			creditCardBillInfoView.onLoad(creditCardBill.getFinanceMonth());
		} else {
			creditCardBillInfoView.onLoad(Util.getThisMonth());
		}
	}
	
	public void setCreditCardBill(CreditCardBill creditCardBill){
		this.creditCardBill = creditCardBill;
		setContent();
	}
	
	private void setContent(){
		if(creditCardBill==null){
			return;
		}
		id = creditCardBill.getId();
		int index = 0;
		for(int i=0;i<cardName.getItemCount();i++){
			String value = cardName.getValue(i);
			if(value.equals(creditCardBill.getItem())){
				index = i;
			}
		}
		cardName.setSelectedIndex(index);
		lastRePayDate.setValue(creditCardBill.getLastRePayDate());
		rePayDate.setValue(creditCardBill.getRePayDate());
		minRePay.setText(Util.intToStr(creditCardBill.getMinRePay()));
		actualRePay.setText(Util.intToStr(creditCardBill.getActualRePay()));
		overAmount.setText(Util.intToStr(creditCardBill.getOverAmount()));
		interest.setText(Util.intToStr(creditCardBill.getInterest()));
		overCost.setText(Util.intToStr(creditCardBill.getOverCost()));
		excess.setText(Util.intToStr(creditCardBill.getExcess()));
		takeAmount.setText(Util.intToStr(creditCardBill.getTakeAmount()));
		takeDate.setValue(creditCardBill.getTakeDate());
		index = 0;
		for(int i=0;i<financeMonth.getItemCount();i++){
			String value = financeMonth.getItemText(i);
			if(value.equals(creditCardBill.getFinanceMonth())){
				index = i;
			}
		}
		financeMonth.setSelectedIndex(index);
	}
	
	private void setMessage(String msg){
		message.setText(msg);
	}
	
	private boolean isValid(){
		setMessage("");
		int index = cardName.getSelectedIndex();
		String value = cardName.getValue(index);
		if("0".equals(value)){
			cardName.setFocus(true);
			setMessage("没有选择卡类型");
			return false;
		}
		index = financeMonth.getSelectedIndex();
		value = financeMonth.getValue(index);
		if("0".equals(value)){
			financeMonth.setFocus(true);
			setMessage("没有选择财务月");
			return false;
		}
		String check = Util.validInput(lastRePayDate.getTextBox().getText());
		if(null != check){
			lastRePayDate.setFocus(true);
			setMessage("" + check);
			return false;
		}
		check = Util.validInput(minRePay.getText());
		if(null != check){
			minRePay.setFocus(true);
			setMessage("最低还款额" + check);
			return false;
		}
		check = Util.validAmount(minRePay.getText());
		if(null != check){
			minRePay.setFocus(true);
			setMessage(check);
			return false;
		}
		check = Util.validAmount(actualRePay.getText());
		if(null != check){
			actualRePay.setFocus(true);
			setMessage(check);
			return false;
		}
		check = Util.validInput(overAmount.getText());
		if(null != check){
			overAmount.setFocus(true);
			setMessage("超限费" + check);
			return false;
		}
		check = Util.validAmount(overAmount.getText());
		if(null != check){
			overAmount.setFocus(true);
			setMessage(check);
			return false;
		}
		check = Util.validInput(interest.getText());
		if(null != check){
			interest.setFocus(true);
			setMessage("利息" + check);
			return false;
		}
		check = Util.validAmount(interest.getText());
		if(null != check){
			interest.setFocus(true);
			setMessage(check);
			return false;
		}
		check = Util.validInput(overCost.getText());
		if(null != check){
			overCost.setFocus(true);
			setMessage("手续费" + check);
			return false;
		}
		check = Util.validAmount(overCost.getText());
		if(null != check){
			overCost.setFocus(true);
			setMessage(check);
			return false;
		}
		check = Util.validInput(excess.getText());
		if(null != check){
			excess.setFocus(true);
			setMessage("余额" + check);
			return false;
		}
		check = Util.validAmount(excess.getText());
		if(null != check){
			excess.setFocus(true);
			setMessage(check);
			return false;
		}
		return true;
	}
}
